import os
import sys

from PyQt6.QtCore import Qt, QDir
from PyQt6.QtGui import QIcon, QFileSystemModel, QStandardItemModel, QStandardItem, QPixmap
from PyQt6.QtWidgets import QMainWindow, QAbstractItemView, QMdiSubWindow, QPlainTextEdit, QLabel, QSizePolicy
from docx import Document
from text_process_ui import Ui_text_process


class TextProcess(Ui_text_process, QMainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle("文本分析器")
        self.setWindowIcon(QIcon('img.png'))

        self.setWindowFlags(Qt.WindowType.MSWindowsFixedSizeDialogHint | Qt.WindowType.WindowStaysOnTopHint)
        self.mdiArea.subWindowActivated.connect(self.updateMenuBar)
        self.save.setShortcut("Ctrl+S" if sys.platform == 'darwin' else "Meta+s")
        self.save.triggered.connect(self.saveDoc)

        self.read_info.setShortcut("Ctrl+R" if sys.platform == 'darwin' else "Meta+s")
        self.read_info.triggered.connect(self.readInfo)

        # 目录
        self.dirModel = QFileSystemModel()
        self.dirModel.setRootPath('')
        # 仅保留目录（文件夹）过滤当前目录和父目录
        self.dirModel.setFilter(QDir.Filter.AllDirs | QDir.Filter.NoDotAndDotDot)
        # 设置文件目录
        self.treeView.setModel(self.dirModel)
        self.treeView.setHeaderHidden(True)
        self.mdiArea.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.centralwidget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.treeView.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.treeView2.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        self.centralwidget.setLayout(self.horizontalLayout)
        for col in range(1, 4):
            self.treeView.setColumnHidden(col, True)
            self.treeView.doubleClicked.connect(self.showFiles)
            self.curPath = "/Users/miaomiaole/Code" if sys.platform == 'darwin' else "D:/code"
            self.curFile = ""
            dirList = self.curPath.split("/")
            defPath = ""
            for dir in dirList:
                if len(dir) > 0:
                    dir = "/" + dir

                defPath += dir
                # 逐级展开
                if defPath == "":
                    defPath = defPath + "/"
                # 逐级展开
                self.treeView.setExpanded(self.dirModel.index(defPath), 1)

        self.fileMode = QStandardItemModel()
        self.treeView2.setModel(self.fileMode)
        # 属性指示在任何情况下都不允许编辑(不能通过键盘，鼠标操作类目）
        self.treeView2.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.treeView2.doubleClicked.connect(self.showContent)
        self.initFileModel()
        self.resText = ''

    def initFileModel(self):
        self.fileMode.clear()
        self.textType = QStandardItem('文本')
        self.fileMode.appendRow(self.textType)

        self.wordType = QStandardItem('word 文档')
        self.fileMode.appendRow(self.wordType)

        self.html = QStandardItem('网页')
        self.fileMode.appendRow(self.html)

        self.image = QStandardItem('图片')
        self.fileMode.appendRow(self.image)

        self.image = QStandardItem('图片')
        self.fileMode.appendRow(self.image)

        self.other = QStandardItem('其它')
        self.fileMode.appendRow(self.other)

        self.curFile = ''
        self.updateStatus()

    def showContent(self, index):
        self.curFIle = self.fileMode.itemData(index)[0]
        # 更新文件状态
        self.updateStatus()
        path = self.curPath + "/" + self.curFIle
        type = self.curFIle.split('.')[1]
        if type == 'txt' or type == 'docx' or type == 'htm' or type == 'html':
            content = ''
            if type != 'docx':
                with open(path, 'r', encoding='utf-8') as f:
                    content = f.read()
            elif type == 'docx':
                doc = Document(path)
                for p in doc.paragraphs:
                    content += p.text
                    content += '\n'
            # 创建子窗口及标题
            textDoc = QMdiSubWindow(self)
            textDoc.setWindowTitle(path)
            # 创建单行输入框
            teContent = QPlainTextEdit(textDoc)
            teContent.setPlainText(content)
            textDoc.setWidget(teContent)
            self.mdiArea.addSubWindow(textDoc)
            textDoc.show()
        elif type == 'jpg' or type == 'jpeg' or type == 'png' or type == 'gif' or type == 'bmp' or type == 'ico':
            picDoc = QMdiSubWindow(self)
            picDoc.setWindowTitle(path)
            lbContent = QLabel(picDoc)
            lbContent.setPixmap(QPixmap(path))
            picDoc.setWidget(lbContent)
            self.mdiArea.addSubWindow(picDoc)
            picDoc.show()



    def showFiles(self, index):
        self.initFileModel()
        self.curPath = self.dirModel.filePath(index)
        fileSet = os.listdir(self.curPath)
        for i in range(len(fileSet)):
            if not os.path.isdir(self.curPath + '/' + fileSet[i]):
                if (fileSet[i].startswith('.')):
                    continue
                fileItem = QStandardItem(fileSet[i])
                type = fileSet[i].split('.')[1]
                if type == 'txt':
                    self.textType.appendRow(fileItem)
                elif type == 'html':
                    self.html.appendRow(fileItem)
                elif type == 'docx':
                    self.wordType.appendRow(fileItem)
                elif type == 'htm' or type == 'html':
                    self.html.appendRow(fileItem)
                elif type == 'jpg' or type == 'png' or type == 'jpeg' or type == 'gif' or type == 'bmp' or type == 'ico':
                    self.image.appendRow(fileItem)
                else:
                    self.other.appendRow(fileItem)
        self.treeView2.expandAll()
        self.updateStatus()

    def updateMenuBar(self):
        print("=======")

    def saveDoc(self):
        print("saveDoc")

    def readInfo(self):
        print("read Info")

    def updateStatus(self):
        print("update Status")
